﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
//using DHQGHN.DAL.Models.Admin;
using DHQGHN.PM0.Controllers;
using WebMatrix.WebData;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;
using DHQGHN.PM0.Security;
using System.Web.Configuration;
using System.Net.Mail;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class UsersController : BaseController
    {
        UserBO userBO;
        //
        // GET: /Users/
        public ActionResult Index(UserModel uModel = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", int currentId = -1)
        {
            SetActiveMenu("/Users/Index");
            if (uModel == null) uModel = new UserModel();
            uModel.Status = 2;
            var model = search(uModel, pageIndex, currentId, false);
            //ViewBag.lstPeopleType = getListPeopleType();
            ViewBag.lstStatus = getListStatus();
            ViewBag.lstApp = CommonData.getListApp();
            return View("~/Views/Users/Users.cshtml", model);
        }

        private IEnumerable<SelectListItem> getListStatus()
        {
            List<SelectListItem> lstItems = new List<SelectListItem>();
            lstItems.AddRange(new[]{
                new SelectListItem() { Text = "Tất cả", Value = "2" },
                new SelectListItem() { Text = "Đang sử dụng", Value = "1" },
                            new SelectListItem() { Text = "Không sử dụng", Value = "0" }
            });
            return new SelectList(lstItems, "Value", "Text");
        }

        [HttpPost]
        public ActionResult actionSearch(UserModel uModel = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", int currentId = -1)
        {
            if (uModel == null) uModel = new UserModel();

            var model = new DataPage<UserModel>();
            while (model.Data.Count() == 0 && pageIndex >= 0)
            {
                model = search(uModel, pageIndex, currentId, false);
                pageIndex--; //load lai trang truoc neu xoa het trang sau
            }
            ViewBag.lstStatus = getListStatus();
            return PartialView("~/Views/Users/_UserList.cshtml", model);
        }

        /// <summary>
        /// Hiển thị form thêm mới người dùng
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost]
        //[CustomAuthorize]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public ActionResult actionPrepareCreateOrAddUser(int? userId)
        {
            ViewBag.lstApp = CommonData.getListApp();
            UserModel user = null;
            if (userId != null && userId > -1)
            {
                userBO = new UserBO();
                user = new UserModel(userBO.GetUserById(userId));
            }
            if (user == null)
            {
                user = new UserModel()
                {
                    UserName = "",
                    FullName = "",
                    Email = "",
                    //Password = "",
                    //ConfirmPassword = "",
                    RegDate = "",
                    ID = -1,
                    IsActive = 1
                };
            }
            if (Request.IsAjaxRequest())
            {
                return PartialView("~/Views/Users/_AddUser.cshtml", user);
            }

            return View(user);
        }

        [HttpPost]
        public ActionResult actionPrepareListRoleByUserId(int userId)
        {
            UserModel user = null;
            ViewBag.lstRoleByUserId = getRoleNameByUserId(userId);
            ViewBag.lstAppByUserId = getAppNameByUserId(userId);
            ViewBag.lstUserName = getUserNameByUserId(userId);

            if (Request.IsAjaxRequest())
            {
                return PartialView("~/Views/Users/Index.cshtml", user);
            }

            return View(user);
        }

        private List<UserModel> getUserNameByUserId(int userId)
        {
            UserBO userBO = new UserBO();
            //string lstUserName = userBO.GetUserNameByUserId(userId);           
            //return lstUserName;
            var lstUserName = userBO.GetUserNameByUserId(userId);
            List<UserModel> lstItems = new List<UserModel>();
            foreach (var user in lstUserName)
            {
                lstItems.Add(new UserModel(user));
            }
            return lstItems;
        }

        #region Temp
        //[HttpGet]
        //public ActionResult actionCreateUser()
        //{
        //    if (!WebSecurity.Initialized)
        //    {
        //        WebSecurity.InitializeDatabaseConnection("DHQGHN.DefaultConnection", "Users", "Id", "UserName", autoCreateTables: true);
        //    }
        //    return View();
        //}

        //[HttpPost]
        //public ActionResult actionCreateUser(UserModel model)
        //{
        //    //if (!WebSecurity.Initialized)
        //    //{
        //    //    WebSecurity.InitializeDatabaseConnection("DHQGHN.DefaultConnection", "Users", "Id", "UserName", autoCreateTables: true);
        //    //}
        //    //WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { RegDate = "", Email = model.Email, FullName = model.FullName, IsActive = 1, AppId = model.AppId });
        //    userBO.CreateUser(model.toDALModel());
        //    Response.Redirect("~/Users/Index");
        //    return View();
        //} 
        #endregion

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult actionCreateOrAddUser(UserModel model)
        {
            if (Request.IsAjaxRequest())
            {
                //PasswordGeneratorPm0 gp = new PasswordGeneratorPm0();

                //model.Password = gp.GeneralPassword();

                model.Password = "123456qR@";

                userBO = new UserBO();

                //if (senmail == true)
                //{
                //bool result = userBO.CreateU(new USER_GROUP_CREATE()
                //{
                //    AppCode = model.AppCode,
                //    Email = model.Email,
                //    FullName = model.FullName,
                //    GroupCode = string.Empty,
                //    IsActive = 1,
                //    Password = model.Password,
                //    Type = "A",
                //    UserName = model.UserName
                //});//

                bool result = userBO.CreateUser(model.toDALModel());
                if (result)
                {                   
                    model.Password = "";
                    LogStream.Write<UserModel>(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrAddUser", model);

                    if (model != null && model.ID > -1)
                    {
                        return Json(JsonResponse.Json200("Cập nhật người dùng thành công!"));
                    }
                    else
                    {
                        bool sendmail = true;// SendGmail(model.Email, "Thông tin tài khoản", "UserName: " + model.UserName + " -- Pass: " + model.Password);
                        if (sendmail)
                        {
                            return Json(JsonResponse.Json200("Thêm mới người dùng thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                        }
                    }
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }
                //}
                //else
                //{
                //    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                //}
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(int[] userList)
        {
            if (Request.IsAjaxRequest())
            {
                userBO = new UserBO();
                bool result = userBO.deleteUserCheck(userList);
                if (result)
                {
                    LogStream.Write(GetCurrentUserName(),
                       CommonData.AppName,
                       GetFunction(),
                       CommonData.GetListId(userList),
                       Resources.Localization.ActionDeleteCaption + " - actionDelete");

                    return Json(JsonResponse.Json200("Ngừng sử dụng thành công!"));
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult resetPass(int appId)
        {
            if (Request.IsAjaxRequest())
            {
                userBO = new UserBO();
                var _userBO = userBO.GetUserById(appId);
                PasswordGeneratorPm0 gp = new PasswordGeneratorPm0();
                gp.Minimum = 2;
                gp.Maximum = 4;
                gp.Kytuso = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
                string a = gp.Generate();

                gp.Kytuso = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
                string a1 = gp.Generate();

                gp.Kytuso = "0123456789".ToCharArray();
                string a2 = gp.Generate();

                gp.Kytuso = "!@$^-_()".ToCharArray();
                string a3 = gp.Generate();

                string PassWord = a + a1 + a2 + a3;

                bool senmail = SendGmail(_userBO.Email, "Thông tin tài khoản", "UserName: " + _userBO.UserName + " -- Pass: " + PassWord);

                if (senmail == true)
                {
                    bool result = userBO.ResetPassword(appId, PassWord);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            "Reset password",
                            "Reset password- resetPass");
                        return Json(JsonResponse.Json200("Reset Mật khẩu thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }

                #region Temp
                //UserModel us = new UserModel();
                //us.ID = appId;
                //if (!WebSecurity.Initialized)
                //{
                //    WebSecurity.InitializeDatabaseConnection("DHQGHN.DefaultConnection", "Users", "Id", "UserName", autoCreateTables: true);
                //}

                //SimpleMembershipProvider provider = (SimpleMembershipProvider)Membership.Provider;
                //string username = provider.GetUserNameFromId(us.ID);

                //var token = WebSecurity.GeneratePasswordResetToken(username);

                //WebSecurity.ResetPassword(token, "123456qR@");
                //return Json(JsonResponse.Json200("Reset Mật khẩu thành công!")); 
                #endregion
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult reActive(int appId)
        {
            if (Request.IsAjaxRequest())
            {
                UserModel model = new UserModel();
                userBO = new UserBO();
                bool result = userBO.reActiveUser(appId);
                if (result)
                {
                    //if (model.ID != null && model.ID > -1)
                    if (model != null && model.ID > -1)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(new int[] { appId }),
                            Resources.Localization.ActionActiveCaption + " - reActive");

                        return Json(JsonResponse.Json200("Khôi phục người dùng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json200("Thêm mới người dùng thành công!"));
                    }
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }
            }
            return null;
        }

        private DataPage<UserModel> search(UserModel uModel, int pageIndex, int currentId, bool compareEqual)
        {
            userBO = new UserBO();
            var DALModel = userBO.GetDynamicListPaging(uModel.toDALModel(), PageSize, pageIndex, compareEqual);
            var model = new DataPage<UserModel>();
            var lstItem = DALModel.Data;
            foreach (DHQGHN.DAL.Models.Admin.UserModel app in lstItem)
            {
                model.Data.Add(new UserModel(app));
            }
            UserModel userModel = null;
            if (currentId >= 0 && model.Data.Count > 0)
            {
                userModel = model.Data.Find(user => user.ID == currentId);
                model.CustomData = userModel;
            }
            else
            {
                model.CustomData = uModel;
            }
            if (model.Data.Count > 0)
            {
                //Tao component phan trang
                var pagNative = new Pagination
                {
                    ActionName = "actionSearch",
                    ModelName = "User",
                    CurrentPage = pageIndex,
                    InputSearchId = "",
                    TagetReLoadId = "user-list",

                };
                pagNative.TotalRows = model.Data[0].RecordCount;
                pagNative.CurrentRow = model.Data.Count;
                ViewBag.Pagination = pagNative;
            }
            return model;
        }

        private DataPage<UserModel> searchd(UserModel uModel, int pageIndex, int currentId, bool compareEqual)
        {
            userBO = new UserBO();
            var DALModel = userBO.GetDynamicListPagingd(uModel.toDALModel(), PageSize, pageIndex, compareEqual);
            var model = new DataPage<UserModel>();
            var lstItem = DALModel.Data;
            foreach (DHQGHN.DAL.Models.Admin.UserModel app in lstItem)
            {
                model.Data.Add(new UserModel(app));
            }
            UserModel userModel = null;
            if (currentId >= 0 && model.Data.Count > 0)
            {
                userModel = model.Data.Find(user => user.ID == currentId);
                model.CustomData = userModel;
            }
            else
            {
                model.CustomData = uModel;
            }
            if (model.Data.Count > 0)
            {
                //Tao component phan trang
                var pagNative = new Pagination
                {
                    ActionName = "actionSearch",
                    ModelName = "User",
                    CurrentPage = pageIndex,
                    InputSearchId = "",
                    TagetReLoadId = "user-list",

                };
                pagNative.TotalRows = model.Data[0].RecordCount;
                pagNative.CurrentRow = model.Data.Count;
                ViewBag.Pagination = pagNative;
            }
            return model;
        }

        public JsonResult CheckExistUserName(string UserName, int? ID, int AppId)
        {
            var isExist = false;
            if (!string.IsNullOrEmpty(UserName))
            {
                userBO = new UserBO();
                isExist = userBO.CheckUserExist(UserName, AppId);
            }
            if (isExist)
            {
                return Json(Resources.Localization.UserNameExist);
            }
            else
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }


        }

        public List<RoleModel> getRoleNameByUserId(int userId)
        {
            RoleBO userBO = new RoleBO();
            var lstRoleName = userBO.GetRoleNameByUserId(userId);
            List<RoleModel> lstItems = new List<RoleModel>();
            foreach (var user in lstRoleName)
            {
                lstItems.Add(new RoleModel(user));
            }
            return lstItems;
        }

        public List<ApplicationModel> getAppNameByUserId(int userId)
        {
            ApplicationBO userBO = new ApplicationBO();
            var lstAppName = userBO.GetAppNameByUserId(userId);
            List<ApplicationModel> lstItems = new List<ApplicationModel>();
            foreach (var user in lstAppName)
            {
                lstItems.Add(new ApplicationModel(user));
            }
            return lstItems;
        }

        private string GetFunction()
        {
            return "Quản trị người dùng - UsersController";
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult AccountChangePass()
        {
            ViewBag.ExceptionPass = WebConfigurationManager.AppSettings["ExceptionPass"];
            return PartialView();
        }

        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public JsonResult SaveChangePass(string PassWord)
        {
            USER_GROUP_CREATE ret = new USER_GROUP_CREATE();
            ret.UserName = GlobalInfo.User.UserName;
            ret.Password = PassWord;
            ret.FullName = "";
            ret.AppCode = "TKTHDS.PM0";
            userBO = new UserBO();

            return Json(userBO.RegisterUser(ret), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public JsonResult CheckPassUserName(string PassWord)
        {
            try
            {
                if (!string.IsNullOrEmpty(PassWord))
                {
                    userBO = new UserBO();
                    string salt = userBO.GetPasswordSalt(GlobalInfo.User.UserName, CommonData.AppCode);
                    bool success = userBO.Login(GlobalInfo.User.UserName, PassWord + salt, "TKTHDS.PM0");
                    return Json(success, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private bool SendGmail(string emailTo, string subject, string body)
        {
            try
            {
                string userName = WebConfigurationManager.AppSettings["PFUserName"];
                string PassWord = WebConfigurationManager.AppSettings["PFPassWord"];
                string Gmail = WebConfigurationManager.AppSettings["PFGmail"];
                string SMTPServer = WebConfigurationManager.AppSettings["SMTPServer"];
                string SMTPPort = WebConfigurationManager.AppSettings["SMTPPort"];

                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(SMTPServer);

                mail.From = new MailAddress(Gmail); //sample@gmail.com
                mail.To.Add(emailTo);
                mail.Subject = subject;
                mail.Body = body;

                SmtpServer.Port = Convert.ToInt32(SMTPPort);
                SmtpServer.Credentials = new System.Net.NetworkCredential(userName, PassWord);
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                return true;
                //MessageBox.Show("mail Send");
            }
            catch
            {
                return false;
            }
        }

        [HttpPost]
        public JsonResult CheckEmail(string Email)
        {
            userBO = new UserBO();
            var _userBO = userBO.CheckEmail(Email, CommonData.AppCode);

            if (_userBO == false)
            {
                return Json("Email đã tồn tại trong hệ thống");
            }
            else
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
        }
    }
}